package com.cgbl.cg.vm.mine

import android.app.Application
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.WorkServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.CourseBean
import com.robot.base.model.PageListBean
import com.robot.base.model.WorksBean
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class PersonalWorksViewModel(application: Application) : GLBaseViewModel(application) {

    val tabType = ObservableInt(TAB_ALL)

    val clickSelectAll = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_ALL)
        checkType = ""
        refresh()
    })

    val clickSelectPass = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_PASS)
        checkType = "1"
        refresh()
    })

    val clickSelectReject = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_REJECT)
        checkType = "2"
        refresh()
    })

    val clickSelectPending = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_PENDING)
        checkType = "0"
        refresh()
    })

    val uc = UiChangeEvent()

    var page = 1

    val pageSize = 10

    var checkType = ""


    class UiChangeEvent {

        val newWorksData: SingleLiveEvent<List<WorksBean>> = SingleLiveEvent()

        val loadMoreWorksData: SingleLiveEvent<List<WorksBean>> = SingleLiveEvent()

    }

    fun refresh() {
        page = 1
        fetchWork()
    }

    fun loadMore() {
        page++
        fetchWork()
    }

    fun fetchWork() {
        WorkServiceFactory.page(
            mapOf(
                "pageNo" to page,
                "pageSize" to pageSize,
                "checkType" to checkType,
                "isAccount" to "1"
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<WorksBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<WorksBean>>) {
                if (page == 1) {
                    uc.newWorksData.postValue(t.data.list)
                } else {
                    uc.loadMoreWorksData.postValue(t.data.list)
                }
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                uc.newWorksData.postValue(listOf())
            }
        })
    }


    companion object {

        const val TAB_ALL = 1

        const val TAB_PASS = 2

        const val TAB_REJECT = 3

        const val TAB_PENDING = 4

    }


}